<template>
  <div class="content_main">
    <el-row :gutter="20">
      <el-col :span="5">
        <div class="content-left">

          <div class="tags">
            <el-card>
              <div slot="header" class="clearfix">
                <span>相关标签</span>
              </div>
              <el-tag v-for="(item,index) in related.tags" style="margin: 5px;cursor:pointer" :key="index"
                      class="hvr-glow">
                <span @click="TheLabel(item)" v-text="item" style="font-size: 18px"></span>
              </el-tag>
            </el-card>

          </div>
        </div>
        <div class="content-left">
          <el-card>
            <div slot="header" class="clearfix">
              <span>相关分类</span>
            </div>
            <el-tag v-for="(item,index) in related.classify" style="margin: 5px;cursor:pointer" :key="index"
                    class="hvr-glow">
              <span @click="Classification(item)" v-text="item" style="font-size: 18px;"></span>
            </el-tag>
          </el-card>
        </div>
      </el-col>
      <el-col :span="14">
        <div class="content-center">

          <div class="ql-container ql-snow">
            <div class="ql-editor">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <h1 v-text="articleInfoById.articleTitle"></h1>
                  <el-alert
                    type="info"
                    :closable="false"
                    effect="dark">
                    <div class="create-date">
                      <span class="article-user"><i class="el-icon-s-custom"></i> <b>{{
                          articleInfoById.articleUsername
                        }}</b></span>
                      <time><i class="el-icon-time" style="margin-left: 15px"></i> 发布时间: {{
                          articleInfoById.createTime
                        }}
                      </time>
                      <span class="article-view" style="margin-left: 15px"><i
                        class="el-icon-view"></i> 浏览量: {{ articleInfoById.articleNum }}</span>
                    </div>
                    <br>
                    <div class="article-tags">
                      标签: <span v-for="(item,index) in JSON.parse(articleInfoById.articleTags)" :key="index">
                      <el-tag @click="TheLabel(item)" style="margin-left: 5px;cursor:pointer" size="mini">{{
                          item
                        }}</el-tag>
                    </span>
                    </div>
                    <div>
                      <el-button size="mini" @click="readContent">读取文本</el-button>
                      <el-button size="mini" @click="stopReadContent">停止</el-button>
                    </div>
                  </el-alert>
                </div>
                <span v-html="articleInfoById.articleContent" class="text item"></span>
                <div class="like">
                  <!--                  踩-->
                  <img v-if="ifTrample.code===404" @click="NoTrample()" src="@/assets/icon/未点赞.png" class="Trample">
                  <img v-if="ifTrample.code===200" @click="IsTrample()" src="@/assets/icon/已点赞.png" class="Trample">
                  <span class="praise">{{ this.articleInfoById.articleUnlike }}</span>
                  <!--                  点赞-->
                  <img v-if="ifLike.code===404" @click="NoLike()" src="@/assets/icon/未点赞.png">
                  <img v-if="ifLike.code===200" @click="IsLike()" src="@/assets/icon/已点赞.png">
                  <span class="praise">{{ this.articleInfoById.articleLike }}</span>
                  <!--                  收藏-->
                  <img v-if="ifCollection.code===200" @click="Collected()" src="@/assets/icon/已收藏.png">
                  <img v-if="ifCollection.code===404" @click="Uncollected()" src="@/assets/icon/未收藏.png">
                  <span class="praise">{{ this.articleInfoById.articleCollect }}</span>
                  <br>
                  <br>

                </div>

              </el-card>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="content_right">
          <el-row :gutter="10">
            <!--头像 -->
            <el-col :span="10">
              <div class="redius">
                <el-image :src="articleUsername.userHead"></el-image>
              </div>
            </el-col>
            <!--          用户名and描述  -->
            <el-col :span="14">
              <h2> {{ articleUsername.userName }} </h2>
              <span class="userInfo"> {{ articleUsername.userInfo }} </span>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8"><p>粉丝数</p> {{ articleUsername.userFans }}</el-col>
            <el-col :span="8"><p>文章数</p> {{ articleCount }}</el-col>
            <el-col :span="8"><p>获赞数</p> {{ praise }}</el-col>
          </el-row>
          <br>
          <el-row>
            <el-button v-if="isFocus.code === 200" @click="cancelFocusOn()">取消关注</el-button>
            <el-button v-if="isFocus.code === 404" @click="addFocusOn()">关 注</el-button>
          </el-row>
        </div>
        <div class="content_right">
          <el-card>
            <div slot="header" class="clearfix">
              <span>相关文章</span>
            </div>
            <div>
              <div v-for="(item,index) in related.articles" style="margin: 5px" :key="index">
                <el-link :href="item.articleId" style="color: #a1d3d7;font-size: 1.1em"
                         v-text="item.articleTitle"></el-link>
              </div>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  addFocus, addLike, addPraise, addRecords,
  cancelFocus,
  getAuthorArticleCount,
  getAuthorInfo, getPraise,
  getRelated, ifTrample,
  isFocus, isHaveLike, trampleAdd
} from "../../request/contentRequest";
import {getUserInfo} from "../../request/request";

const synth = window.speechSynthesis;
const msg = new SpeechSynthesisUtterance();
export default {
  name: "BlogInfo",

  data() {
    return {
      //获取文章信息
      articleInfoById: {
        articleId: 0,
        articleUsername: ""
      },


      //获取文章的作者信息
      articleUsername: {
        createTime: null,
        userAddress: "",
        userBirth: "",
        userEducation: "",
        userEmail: "",
        userFans: "",
        userGender: "",
        userHead: "",
        userInfo: "",
        userLikeTag: "",
        userMajor: "",
        userName: "",
        userPassword: "",
        userPhone: "",
        userRoleId: 0,
        userSchool: "",
        userSchoolTime: "",
        userStatus: 0,
        userVisits: 0,
        usernameId: 0
      },
      //文章数量
      articleCount: 0,
      //点赞数量
      praise: 0,
      isFocus: {
        code: 0,
        msg: '',
      },
      ifCollection: {
        code: 0,
        msg: ''
      },
      ifTrample: {
        code: 0,
        msg: ''
      },
      ifLike: {
        code: 0,
        msg: ''
      },

      //相关的内容
      related: {
        classify: [],
        tags: [],
        articles: [],
      }
    };
  },
  methods: {

    /**
     * 朗读文本
     */
    readContent() {
      msg.text = this.articleInfoById.articleContent;     // 文字内容: 小朋友，你是否有很多问号
      msg.lang = "zh-CN";  // 使用的语言:中文
      msg.volume = 1;      // 声音音量：1
      msg.rate = 1;        // 语速：1
      msg.pitch = 1;       // 音高：1
      synth.speak(msg);    // 播放
    },
    stopReadContent(e) {
      msg.text = e;
      msg.lang = "zh-CN";
      synth.cancel(msg);
    },

    /**
     * 已收藏改为取消收藏
     * @constructor
     */
    Collected() {
      this.$contentReq.addLike(this.$user, this.articleInfoById.articleId).then((data => {
        this.ifCollection.code = data.code
        this.getBlogInfoById(this.$route.params.id)
      }))
    },
    /**
     * 未收藏改为已收藏
     * @constructor
     */
    Uncollected() {
      this.$contentReq.addLike(this.$user, this.articleInfoById.articleId).then((data => {
        this.ifCollection.code = data.code
        this.getBlogInfoById(this.$route.params.id)
      }))
    },
    /**
     * 判断是否已收藏
     */
    ifCollected() {
      this.$contentReq.isHaveLike(this.$user, this.articleInfoById.articleId).then((data) => {
        this.ifCollection.code = data.code
      })
    },
    /**
     * 点击未踩图片变为踩
     * @constructor
     */
    NoTrample() {
      this.$contentReq.trampleAdd(this.$user, this.articleInfoById.articleId).then((data) => {
        this.ifTrample.code = data.code
        this.getBlogInfoById(this.$route.params.id)
      })
    },
    /**
     * 点击图片变为未踩
     * @constructor
     */
    IsTrample() {
      this.$contentReq.trampleAdd(this.$user, this.articleInfoById.articleId).then((data) => {
        this.ifTrample.code = data.code
        this.getBlogInfoById(this.$route.params.id)
      })
    },
    IfTrample() {
      this.$contentReq.ifTrample(this.$user, this.articleInfoById.articleId).then((data) => {
        this.ifTrample.code = data.code
      })
    },
    /**
     * 点击变为点赞状态
     * @constructor
     */
    NoLike() {
      this.$contentReq.addPraise(this.$user, this.articleInfoById.articleId).then((data) => {
        this.ifLike.code = data.code
        this.getBlogInfoById(this.$route.params.id)
      })
    },
    /**
     * 点击变为未点赞状态
     * @constructor
     */
    IsLike() {
      this.$contentReq.addPraise(this.$user, this.articleInfoById.articleId).then((data) => {
        this.ifLike.code = data.code
        this.getBlogInfoById(this.$route.params.id)
      })
    },
    /**
     * 是否已点赞
     */
    ifPraise() {
      this.$contentReq.ifPraise(this.$user, this.articleInfoById.articleId).then((data) => {
        console.log("1324124", data.code);
        this.ifLike.code = data.code
      })
    },
    /**
     * 获取文章信息,按照id
     * @param id 文章id
     */
    getBlogInfoById(id) {
      this.$homeReq.getBlogInfoById(id).then((data) => {
        this.articleInfoById = data.data
        this.getRelated();
        this.ifPraise();
        this.ifCollected();
        this.IfTrample();
        console.log("iahfjkahfaf:", this.articleInfoById)
      })
    },

    /**
     * 获取作者信息,按照文章作者来获取
     */
    getAuthorInfoByArticleAuthor() {
      let reqAuthor = setInterval(() => {
        let articleUsername = this.articleInfoById.articleUsername;
        //如果文章作者名不为undefined才发请求
        if (articleUsername !== undefined) {
          this.$contentReq.getAuthorInfo(articleUsername).then(data => {
            //格式化json
            this.articleUsername = data.data
            console.log('格式化前 = ', data)
            this.articleUsername.userLikeTag = JSON.parse(data.data.userLikeTag)
            console.log('格式化后 = ', data.data.userLikeTag)
            // 等作者信息获取完成
            // 后,在获取用户的关注状态
            console.log('文章作者', this.articleUsername)
            this.isFocusOn();
          });
          //只需要请求一次,清求完成后清除定时器
          clearInterval(reqAuthor)
        }
      }, 10)
    },
    /**
     * 获取作者的文章数量
     */
    getAuthorArticleCount() {
      let articleUsername = this.articleInfoById.articleUsername;
      this.$contentReq.getAuthorArticleCount(articleUsername).then((data) => {
        this.articleCount = data.data
      })
    },

    /**
     * 获取所有的文章的点赞数量
     */
    getPraise() {
      let articleUsername = this.articleInfoById.articleUsername;
      this.$contentReq.getPraise(articleUsername).then(data => {
        this.praise = data.data[0]
      })
    },
    /**
     * 取消关注
     */
    cancelFocusOn() {
      this.$contentReq.cancelFocus(this.articleUsername.usernameId, this.loginUserId).then(data => {
        console.log('点取消关注 = ', data);
        //刷新一下关注状态 刷新一下作者信息
        this.isFocusOn();
        this.getAuthorInfoByArticleAuthor()
      })
    },

    /**
     * 添加到关注
     */
    addFocusOn() {
      this.$contentReq.addFocus(this.articleUsername.usernameId, this.loginUserId).then(data => {
        //刷新一下关注状态 刷新一下作者信息
        this.isFocusOn();
        this.getAuthorInfoByArticleAuthor()
      })
    },

    /**
     * 发送是否已关注请求
     */
    isFocusOn() {
      let loginUserId;
      // 先查询到自己的信息
      this.$request.getUserInfo(this.$user).then(data => {
        loginUserId = data.data.usernameId
        this.loginUserId = data.data.usernameId
        // 查询是否已关注
        this.$contentReq.isFocus(this.articleUsername.usernameId, loginUserId).then(data => {
          //未关注
          if (data.code === 404) {
            this.isFocus.code = data.code;
            this.isFocus.msg = '未关注';
            return
          }
          //200
          this.isFocus.code = data.code;
          this.isFocus.msg = '已关注';
        })
      })


    },


    /**
     * 获取相关内容
     */
    getRelated() {
      let articleTags = JSON.parse(this.articleInfoById.articleTags);
      this.$contentReq.getRelated(articleTags.join(',')).then(data => {
        // todo 将内容渲染到指定页面
        console.log('相关内容 = ', data)
        let relatedTags = data.data.relatedTags;
        let relatedClassify = data.data.relatedClassify;
        //将标签存到数组中
        let tags = []
        this.related.articles = data.data.relatedArticleTitle;
        for (let i = 0; i < relatedTags.length; i++) {
          for (let j = 0; j < JSON.parse(relatedTags[i]).length; j++) {
            tags.push(JSON.parse(relatedTags[i])[j])
          }
        }
        this.related.tags = this.removeDuplicate(tags)
        this.related.classify = this.removeDuplicate(relatedClassify)
      })
    },

    /**
     * 去除数组中重复的数据
     * @param arr 数组
     */
    removeDuplicate(arr) {
      if (arr === null || arr.length === 0) {
        return arr
      }

      let set = new Set
      for (let i = 0; i < arr.length; i++) {
        set.add(arr[i])
      }
      return Array.from(new Set(arr))
    },
    /**
     * 点击相关标题跳转
     * @constructor
     */
    TheLabel(item) {
      this.$router.push({
        path: `/tagsArticle/${item}`,
      })
    },
    Classification(item) {
      this.$router.push({
        path: `/blogTags/${item}`,

      })
    },
    //文章浏览十秒添加一次浏览量
    addRecords() {
      this.$contentReq.addRecords(this.articleInfoById.articleUsername, this.articleInfoById.articleId).then((data => {
      }))
    }
  },

  created() {
    //获取路径参数
    let id = this.$route.params.id;
    this.getBlogInfoById(id)
    setTimeout(() => {
      this.getAuthorInfoByArticleAuthor()
      this.getAuthorArticleCount()
      this.getPraise()
    }, 800)

    setTimeout(() => {
      this.addRecords()
    }, 1000 * 10)
  }

}
</script>

<style scoped>
.like > img {
  height: 30px;
  width: 30px;
  float: right;
  padding: 5px;
  cursor: pointer
}

.praise {
  float: right;
  transform: translate(-50px)
}

.like {
  height: 43px;
}

.like > img.Trample {
  -ms-transform: rotate(180deg); /* IE 9 */
  -webkit-transform: rotate(180deg); /* Safari and Chrome */
  transform: rotate(180deg);
}

.userInfo {
  display: block;
  height: 50px;
  overflow: hidden;
  color: rgb(147, 147, 147);
  text-overflow: ellipsis;
  white-space: nowrap;
}

.content_main {
  width: 90%;
  min-height: 300px;
  border-radius: 10px;
  border: 1px solid #ffdf5f;
  margin: 40px auto auto;
}

.content-left, .content-center, .content_right {
  width: 100%;
  min-height: 300px;
  border: 1px solid red;
  margin-top: 10px;
}

.redius {
  width: 110px;
  height: 110px;
  border-radius: 100px;
  overflow: hidden;
}

.redius img {
  width: 100%;
  height: 100%;
}

.content_right {
}
</style>
